<?php

class Horario
{
  private $party_start, $party_end, $jornada_start, $jornada_end;
  private $jornadas = array();
  
  public function __construct($party_start, $party_end, $jornada_start, $jornada_end) {
    $this->party_start = $party_start;
    $this->party_end = $party_end;
    $this->jornada_start = $jornada_start;
    $this->jornada_end = $jornada_end;
    
    $this->generar_jornadas();
  }
  
  
  public function add_actividad($nid, $hid, $title, $description, $comienzo, $fin, $taxonomy) {
    foreach($this->jornadas as $jornada) {
      if($jornada->hora_en_jornada($comienzo)) {
        $jornada->add_actividad($nid, $hid, $title, $description, $comienzo, $fin, $taxonomy);
      }
    }
  }
  
  
  public function get_html() {
    foreach($this->jornadas as $jornada) {
      $output .= $jornada->get_html();
    }
    
    return $output;
  }
  
  
  public function get_index_html() {
    $output = '<ul>';
    foreach($this->jornadas as $jornada) {
      date_default_timezone_set('GMT');
      setlocale(LC_TIME, "es_ES.UTF-8");
      $start = $jornada->get_start();
      $output .= '<li>' . l(strftime('%A, %e de %B de %G', date_array2unix($start)), 'horario', null, null, date('dmY', date_array2unix($start))) . '</li>';
    }
    $output .= '</ul>';
    
    return $output;
  }
  
  public function get_caption_html() {
    $header = array('data' => '');
    
    $rows[] = array(array(
      'data' => t('<strong>Campeonatos</strong>: torneos de juegos PC, consolas, etc.'),
      'style' => 'background: transparent url(modules/contrib/pq_horario/images/campeonato_back.png) repeat top left',
    ));
    $rows[] = array(array(
      'data' => t('<strong>Charlas</strong>: conferencias y demostraciones.'),
      'style' => 'background: transparent url(modules/contrib/pq_horario/images/charla_back.png) repeat top left',
    ));
    $rows[] = array(array(
      'data' => t('<strong>Concursos</strong>: competiciones que no son campeonatos.'),
      'style' => 'background: transparent url(modules/contrib/pq_horario/images/concurso_back.png) repeat top left',
    ));
    $rows[] = array(array(
      'data' => t('<strong>Exterior</strong>: actividades realizadas fuera del pabellón.'),
      'style' => 'background: transparent url(modules/contrib/pq_horario/images/exterior_back.png) repeat top left',
    ));
    $rows[] = array(array(
      'data' => t('<strong>Organización</strong>: eventos de la party como comidas, inauguración, clausura, etc.'),
      'style' => 'background: transparent url(modules/contrib/pq_horario/images/organizacion_back.png) repeat top left',
    ));
    $rows[] = array(array(
      'data' => t('<strong>Talleres</strong>: talleres prácticos y demostraciones.'),
      'style' => 'background: transparent url(modules/contrib/pq_horario/images/taller_back.png) repeat top left',
    ));
  
    return theme_table($header, $rows);
  }
  
  public function get_plain() {
    $output = "PARTY QUIJOTE 2008\nHORARIO DE ACTIVIDADES\n\n";
    foreach($this->jornadas as $jornada) {
      $foo = $jornada->get_plain();
      if($foo != '') {
        $output .= $foo . "\n\n";
      }
    }
    
    return $output;
  }
  
  
  private function generar_jornadas() {
    $foo_start = $this->party_start;
    
    $jornada_start = ($this->jornada_start['hours'] * 60) + $this->jornada_start['minutes'];
    $jornada_end = ($this->jornada_end['hours'] * 60) + $this->jornada_start['minutes'];
    if($jornada_start < $jornada_end) {
      $foo_end = $this->party_start;
      $foo_end['hours'] = $this->jornada_end['hours'];
      $foo_end['minutes'] = $this->jornada_end['minutes'];
    } else {
      $foo_end = $this->party_start;
      $foo_end['mday'] += 1;
      $foo_end['hours'] = $this->jornada_end['hours'];
      $foo_end['minutes'] = $this->jornada_end['minutes'];
    }
    
    $condicion = true;
    while($condicion) {
      if($this->day_eq($this->party_end, $foo_start)) {
        $foo_end = $this->party_end;
        $condicion = false;
      }
      
      $this->jornadas[] = new Jornada($foo_start, $foo_end);
      
      $foo_start['mday'] += 1;
      $foo_start['hours'] = $this->jornada_start['hours'];
      $foo_start['minutes'] = $this->jornada_start['minutes'];
      
      $foo_end['mday'] += 1;
      $foo_end['hours'] = $this->jornada_end['hours'];
      $foo_end['minutes'] = $this->jornada_end['minutes'];
    }
  }
  
  
  private function day_eq($fecha1, $fecha2) {
    if(($fecha1['year'] == $fecha2['year']) &&
       ($fecha1['month'] == $fecha2['month']) &&
       ($fecha1['mday'] == $fecha2['mday'])) {
      return true;
    } else {
      return false;
    }
  }
}


class Jornada
{
  private $start, $end;
  private $bloques = array();
  
  public function __construct($tm_start, $tm_end) {
    $this->start = $tm_start;
    $this->end = $tm_end;
    
    $this->generar_bloques();
  }
  
  private function generar_bloques() {
    include_once(drupal_get_path('module', 'date_api') .'/date.inc');
    
    $start = date_array2unix($this->start);
    $end = date_array2unix($this->end);
    
    for($i=$start; $i <= $end; $i += 1800) {
      $this->bloques[$i] = array(
        'actividades' => array(),
        'act_a_medias' => 0,
      );
    }
  }
  
  public function hora_en_jornada($comienzo) {
    return array_key_exists($comienzo, $this->bloques);
  }
  
  public function add_actividad($nid, $hid, $title, $description, $comienzo, $fin, $taxonomy) {
    $num_bloques = ($fin - $comienzo) / 1800;
    
    $this->bloques[$comienzo]['actividades'][] = array(
      'nid' => $nid,
      'hid' => $hid,
      'title' => $title,
      'description' => $description,
      'num_bloques' => $num_bloques,
      'taxonomy' => $taxonomy,
    ); 
    
    for($i = $comienzo + 1800; $i < $fin; $i += 1800) {
      $this->bloques[$i]['act_a_medias'] += 1;
    }
  }

  
  public function get_html() {
    $num_columnas = $this->columnas_jornada();
    
    date_default_timezone_set('GMT');
    setlocale(LC_TIME, "es_ES.UTF-8");
    $fecha_jornada = strftime('%A, %e de %B de %G', date_array2unix($this->start));
    $header = array(
      'data' => t('Hora'),
      array(
        'data' => $fecha_jornada,
        'class' => 'fecha',
        'colspan' => $num_columnas,
      ),
    );
    
    foreach($this->bloques as $hora => $bloque) {
      $row = array();
      $row[] = array(
        'data' => date('H:i', $hora),
        'class' => 'hour',
      );
      
      if($num_columnas == 0) {
        $row[] = array(
          'data' => '',
        );
      }
      
      $cols_blanco = $num_columnas - count($bloque['actividades']) - $bloque['act_a_medias'];
      foreach($bloque['actividades'] as $actividad) {
        
        $act_data = l($actividad['title'], 'node/'.$actividad['nid']);
        $url_image = drupal_get_path('module', 'pq_horario') . '/images/';
        if(user_access('administrar horario')) {
          $nid = $actividad['nid'];
          $hid = $actividad['hid'];
          $img_editar = sprintf('<img src=%s height="16px" weight="16px" />', $url_image . 'editar.png');
          $img_eliminar = sprintf('<img src=%s height="16px" weight="16px" />', $url_image . 'eliminar.png');
          $act_data .= '&nbsp;' . l($img_editar, "node/$nid/horario/edit/$hid", array('title' => t('editar')), null, null, null, true);
          $act_data .= l($img_eliminar, "node/$nid/horario/delete/$hid", array('title' => t('eliminar')), null, null, null, true);
        }
        if(!is_null($actividad['description']) && $actividad['description'] != '') {
          $act_data .= sprintf('<div class="description">%s</div>', $actividad['description']);
        }

        $back_url = $url_image . $actividad['taxonomy'] . '_back.png';
        $back_image = sprintf('background: transparent url(%s) repeat top left', $back_url);
        if($actividad['num_bloques'] > 1) {
          $row[] = array(
            'data' => $act_data,
            'rowspan' => $actividad['num_bloques'],
            'class' => 'actividad',
            'style' => $back_image,
          );
        } else {
          $row[] = array(
            'data' => $act_data,
            'class' => 'actividad',
            'style' => $back_image,
          );
        }
      }

      if($cols_blanco != 0) {
        for($i=0; $i<$cols_blanco; $i++)
        $row[] = array(
          'data' => '',
        );
      }
      
      $rows[] = $row;
    }
    
    $output .= theme_table($header, $rows, array(
      'id' => date('dmY', date_array2unix($this->start)),
      'class' => 'pq_horario')
    );
    return $output;
  }

  
  public function get_plain() {
    date_default_timezone_set('GMT');
    setlocale(LC_TIME, "es_ES.UTF-8");
    $fecha_jornada = strftime('%A, %e de %B de %G', date_array2unix($this->start));
    
    $output = '';
    foreach($this->bloques as $hora => $bloque) {
      if(count($bloque['actividades']) != 0) {
        $output .= date('H:i', $hora);
        
        $output_act = '';
        foreach($bloque['actividades'] as $actividad) {
          $duration = $this->get_duration_string($actividad['num_bloques']);
          $output_act .= "\t" . t('%activity (%duration)', array('%activity' => $actividad['title'], '%duration' => $duration)) .  "\n";
        }
        
        if($output_act == '') {
          $output .= "\n";
        } else {
          $output .= $output_act;        
        }
      }
    }
    
    if($output != '') {
      $output = $fecha_jornada . "\n" . $output;
    }
    
    return $output; 
  }
  
  
  public function get_start() {
    return $this->start;
  }
  
  private function columnas_jornada() {
    $maximo = 0;
    foreach($this->bloques as $bloque) {
      $num_columnas_bloque = $bloque['act_a_medias'] + count($bloque['actividades']);
      if($maximo < $num_columnas_bloque) {
        $maximo = $num_columnas_bloque;
      }
    }
    
    return $maximo;
  }
  
  private function get_duration_string($num_bloques) {
    if($num_bloques <= 1) {
      $output = t('%minutes minutos', array('%minutes' => $num_bloques * 30));
    } else {
      $hours = $num_bloques / 2;
      settype($hours, 'Integer');
      $minutes = ($num_bloques % 2) * 30;
      
      if($hours == 1) {
        $output = t('%hours hora', array('%hours' => $hours));
      } else {
        $output = t('%hours horas', array('%hours' => $hours));
      }
      
      if($minutes != 0) {
        $output .= t(' %minutes minutos', array('%minutes' => $minutes));
      }
    }
    
    return $output;
  }
}